﻿/// <summary>
/// 错误日志
/// 自动记录提示的错误并在工程下建立一个log.txt记录。
/// 缺陷：再次记录时会覆盖文件。
/// new StreamWriter时第二个参数为true可以解决本问题。
/// </summary>

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class DebugManager : MonoBehaviour {

	private StreamWriter sw;

	public string LogFileName="log.txt";
	// Use this for initialization
	void Start () {
		DontDestroyOnLoad(gameObject);
		sw=new StreamWriter(Application.persistentDataPath+"/"+LogFileName，ture);
		Debug.Log(Application.persistentDataPath+"/"+LogFileName);
	}
	/// <summary>
	/// This function is called when the object becomes enabled and active.
	/// </summary>
	void OnEnable()
	{
		Application.RegisterLogCallback(HandleLog);
	}
	
	/// <summary>
	/// This function is called when the behaviour becomes disabled or inactive.
	/// </summary>
	void OnDisable()
	{
		Application.RegisterLogCallback(null);
	}

	void HandleLog(string logString,string stackTrace,LogType type)
	{
		if(type==LogType.Exception||type==LogType.Error)
		{
			sw.WriteLine("Logged at: "+System.DateTime.Now.ToString()+" - Log Desc: "+logString+" - Trace: "+stackTrace
			+" - Type: "+type.ToString());
		}
	}

	/// <summary>
	/// This function is called when the MonoBehaviour will be destroyed.
	/// </summary>
	void OnDestroy()
	{
		sw.Close();
	}
}
